from rest_framework import serializers
from rest_framework.exceptions import NotFound

from app.models import Cart, ProductSpec


class CartAddSerializer(serializers.ModelSerializer):
    amount = serializers.IntegerField(min_value=0)
    class Meta:
        model = Cart
        fields = '__all__'


class CartUpdateSerializer(serializers.Serializer):
    spec = serializers.PrimaryKeyRelatedField(queryset=ProductSpec.objects.all())
    amount = serializers.IntegerField(min_value=0)


class CartGetResponseSerializer(serializers.BaseSerializer):
    def to_representation(self, instance):
        try:
            spec = ProductSpec.objects.get(pk=instance.spec.id)
        except ProductSpec.DoesNotExist:
            raise NotFound(detail=u'商品规格不存在')

        return {
            'id': instance.id,
            'spec_id': spec.id,  # 商品规格ID
            'spec_name': spec.spec_name,  # 商品规格名
            'product_id': spec.product.id,  # 商品ID
            'product_name': spec.product.name,
            'product_image': spec.product.image_url,
            'discount': spec.discount,
            'deposit': spec.deposit,
            'deposit_desc': spec.deposit_desc
        }
